import bcrypt from 'bcrypt';
import crypto from 'crypto';
import { config } from '../config/index.js';

// ==================== 密码哈希 ====================

/**
 * 哈希密码
 */
export async function hashPassword(password) {
  return bcrypt.hash(password, config.security.bcryptRounds);
}

/**
 * 验证密码
 */
export async function verifyPassword(password, hash) {
  return bcrypt.compare(password, hash);
}

// ==================== 数据加密 ====================

const ALGORITHM = 'aes-256-gcm';
const KEY_LENGTH = 32; // 256 bits
const IV_LENGTH = 16;
const SALT_LENGTH = 64;
const TAG_LENGTH = 16;

/**
 * 生成随机盐值
 */
export function generateSalt(length = SALT_LENGTH) {
  return crypto.randomBytes(length).toString('hex');
}

/**
 * 从用户密码和盐值派生加密密钥
 */
export function deriveKey(password, salt) {
  return crypto.pbkdf2Sync(
    password,
    salt,
    100000, // 迭代次数
    KEY_LENGTH,
    'sha512'
  );
}

/**
 * 加密数据
 * @param {string} text - 要加密的文本
 * @param {Buffer} key - 加密密钥
 * @returns {string} - 加密后的文本 (iv:tag:encrypted)
 */
export function encrypt(text, key) {
  const iv = crypto.randomBytes(IV_LENGTH);
  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
  
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  const tag = cipher.getAuthTag();
  
  // 返回格式: iv:tag:encrypted
  return `${iv.toString('hex')}:${tag.toString('hex')}:${encrypted}`;
}

/**
 * 解密数据
 * @param {string} encryptedData - 加密的数据 (iv:tag:encrypted)
 * @param {Buffer} key - 加密密钥
 * @returns {string} - 解密后的文本
 */
export function decrypt(encryptedData, key) {
  const parts = encryptedData.split(':');
  if (parts.length !== 3) {
    throw new Error('Invalid encrypted data format');
  }
  
  const iv = Buffer.from(parts[0], 'hex');
  const tag = Buffer.from(parts[1], 'hex');
  const encrypted = parts[2];
  
  const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
  decipher.setAuthTag(tag);
  
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  
  return decrypted;
}

// ==================== 令牌密钥加密 ====================

/**
 * 加密TOTP密钥
 */
export function encryptTotpSecret(secret, userPassword, masterKeySalt) {
  const key = deriveKey(userPassword, masterKeySalt);
  return encrypt(secret, key);
}

/**
 * 解密TOTP密钥
 */
export function decryptTotpSecret(encryptedSecret, userPassword, masterKeySalt) {
  const key = deriveKey(userPassword, masterKeySalt);
  return decrypt(encryptedSecret, key);
}

// ==================== 随机码生成 ====================

/**
 * 生成随机令牌
 */
export function generateRandomToken(length = 32) {
  return crypto.randomBytes(length).toString('hex');
}

/**
 * 生成恢复码（格式：XXXX-XXXX-XXXX-XXXX）
 */
export function generateRecoveryCode() {
  const code = crypto.randomBytes(8).toString('hex').toUpperCase();
  return `${code.slice(0, 4)}-${code.slice(4, 8)}-${code.slice(8, 12)}-${code.slice(12, 16)}`;
}

/**
 * 生成多个恢复码
 */
export function generateRecoveryCodes(count = 10) {
  return Array.from({ length: count }, () => generateRecoveryCode());
}

/**
 * 哈希恢复码（存储用）
 */
export async function hashRecoveryCode(code) {
  // 移除连字符
  const cleanCode = code.replace(/-/g, '');
  return hashPassword(cleanCode);
}

/**
 * 验证恢复码
 */
export async function verifyRecoveryCode(code, hash) {
  const cleanCode = code.replace(/-/g, '');
  return verifyPassword(cleanCode, hash);
}

// ==================== UUID验证 ====================

/**
 * 验证UUID格式
 */
export function isValidUUID(uuid) {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
  return uuidRegex.test(uuid);
}


